package org.example.redis.controller;

import cn.hutool.Hutool;
import cn.hutool.crypto.SecureUtil;
import org.example.redis.entity.ApiAccountEntity;
import org.example.redis.service.ApiAccountService;
import org.example.redis.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api_account")
public class ApiAccountController {
    @Autowired
    private ApiAccountService apiAccountService;
    @Value("${salt}")
    private String salt;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //注册账号
    @PostMapping("/register")
    public JsonResult register(@RequestBody ApiAccountEntity account) {//使用@RequestBody注解，将json数据映射为对象
        if(account.getAccount() == null || account.getAccount().trim().isEmpty()){
            return JsonResult.failed("账号不能为空");
        }
        if(account.getPassword() == null || account.getPassword().trim().isEmpty()){
            return JsonResult.failed("密码不能为空");
        }
        //账号重复性验证
        ApiAccountEntity accountInfo = apiAccountService.findByAccount(account.getAccount());
        if(accountInfo != null){
            return JsonResult.failed("该账号已存在，请登录");
        }
        //md5密码加密
        String safePassword = SecureUtil.md5(account.getPassword());
        account.setPassword(safePassword);
        int result = apiAccountService.addApiAccount(account);
        if(result ==0){
            return JsonResult.failed("注册失败");
        }
        return JsonResult.success("注册成功",null);
    }
    //登录
    @PostMapping("/login")
    public JsonResult login(@RequestBody ApiAccountEntity account){
        if(account.getAccount() == null || account.getAccount().trim().isEmpty()){
            return JsonResult.failed("账号不能为空");
        }
        if(account.getPassword() == null || account.getPassword().trim().isEmpty()){
            return JsonResult.failed("密码不能为空");
        }
        ApiAccountEntity accountInfo = apiAccountService.findByAccount(account.getAccount());
        if (accountInfo == null || !accountInfo.getPassword().equals(SecureUtil.md5(account.getPassword()))){
            return JsonResult.failed("账号或密码错误");
        }
        //生成 token，返回给前端（生成规则：盐值+密码）
        String token = SecureUtil.sha256(salt+ account.getPassword());
        //使用redis保存token
        stringRedisTemplate.opsForValue().set(token,token,24*60, TimeUnit.MINUTES);
        return JsonResult.success("登录成功",token);
    }
}
